
const memory = new Map()

function now () { return Date.now() }

export async function get (key) {
  try {
    if (global.redis) {
      const val = await global.redis.get(key)
      if (val != null) return JSON.parse(val)
    }
  } catch {}
  const entry = memory.get(key)
  if (!entry) return null
  if (entry.exp && entry.exp < now()) { memory.delete(key); return null }
  return entry.val
}

export async function set (key, value, ttlMs = 0) {
  try {
    if (global.redis) {
      const payload = JSON.stringify(value)
      if (ttlMs > 0) {
        await global.redis.set(key, payload, 'PX', ttlMs)
      } else {
        await global.redis.set(key, payload)
      }
    }
  } catch {}
  const exp = ttlMs > 0 ? now() + ttlMs : 0
  memory.set(key, { val: value, exp })
}

export async function del (key) {
  try { if (global.redis) await global.redis.del(key) } catch {}
  memory.delete(key)
}